import AccreditDia from '@/components/accreditDia/AccreditDia'
import NoPermissionTem from '@/components/antd-comp/NoPermission'
import ListEmpty from '@/components/antd-comp/empty'
import { showMessage } from '@/components/antd-comp/message'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { typesContext } from '@/contexts/typesContext'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal, Tooltip } from 'antd'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import TabsDropComponent from '../../components/TabsDropComponent/index'
import { FlowType } from '../../types/flow'
import { useTable } from '../../util/hook'
import { flowUsedCountByAstApi, workflowDelApi, workflowListApi } from './API/index'
import FlowCreate from './flowCreate'
import './style/flowCreate.css'
const { confirm } = Modal

// table的唯一id
const getUniqueKey = (record: any) => record.id

export default function FlowListPage() {
  const { t } = useTranslation()
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = ['工作流']
  useRouteStoreHook(routeNames)
  // ------埋点------
  const { skillsBuriedEvent } = useBuriedEvent()
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  const navigate = useNavigate()
  /* 筛选 */
  const [num, setNum] = useState(0) as any
  const [name, setName] = useState(undefined)
  // 类型选择
  const [typeList, setTypeList] = useState([])
  const typeMap = useRef({})
  const [SearchListDialog, setSearchListDialog] = useState([])

  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then(res => {
      if (res) {
        const list = [...res]
        setSearchListDialog(list)
        res.unshift({
          id: 0,
          label: '全部类型',
          value: 'all'
        })
        setTypeList(res)
        const typeInfo = {}
        res.forEach(type => {
          typeInfo[type.id] = type.label
        })
        typeMap.current = typeInfo
      } else {
        setTypeList([
          {
            id: 0,
            label: t('all')
          }
        ])
      }
    })
  }

  // 新工作流的清理功能
  const { loadAllData } = useContext(typesContext)
  useEffect(() => {
    //loadTypeList()
    loadAllData()
    // destroyFlow()
  }, [])
  // ---end---
  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    search,
    reload,
    filterData,
    setLoading
  } = useTable<FlowType>(
    { pageSize: 10 },
    param => workflowListApi(param.page, param.pageSize, param.keyword, num || ''),
    true,
    () => hasFuncPermission([Func.workflow.query])
  )
  const [open, setOpen] = useState(false)
  const [info, setInfo] = useState({})

  const handleDelete = async id => {
    skillsBuriedEvent({
      page: '工作流页面',
      event_name: '【删除】按钮',
      data_id: id
    })
    // 删除权限限制
    if (!hasFuncPermission([Func.workflow.del])) {
      return
    }
    const res: any = await flowUsedCountByAstApi(id)
    const count = res?.count || 0
    // const count = 0
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: `${
        count && count > 0
          ? `工作流当前被${count}个智能体使用。删除后，将导致所有引用的智能体无法使用，操作无法撤回，确认删除该工作流？`
          : '确认删除该工作流'
      } `,
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onCancel() {
        skillsBuriedEvent({
          page: '工作流页面',
          event_name: '取消【删除】工作流按钮',
          data_id: id
        })
      },
      onOk() {
        setLoading(true)
        workflowDelApi(id)
          .then(res => {
            skillsBuriedEvent({
              page: '工作流页面',
              event_name: '确定【删除】工作流按钮',
              data_id: id,
              detail: JSON.stringify({ 结果: '成功' })
            })
            reload()
            showMessage({
              content: '删除成功',
              type: 'success'
            })
          })
          .catch(() => {
            skillsBuriedEvent({
              page: '工作流页面',
              event_name: '确定【删除】工作流按钮',
              data_id: id,
              detail: JSON.stringify({ 结果: '失败' })
            })
            setLoading(false)
          })
      }
    })
  }
  const handleEdit = data => {
    skillsBuriedEvent({
      page: '工作流页面',
      event_name: '【编辑】按钮',
      data_id: data.id
    })
    if (!hasFuncPermission([Func.workflow.edit])) {
      return
    }
    const { name, description, logo, category_code, id } = data
    setInfo({ name, desc: description, logo, category_code, id })
    setOpen(true)
  }

  const seleCarFun = (data, id) => {
    setNum(id)
    filterData({ name, type: id })
    skillsBuriedEvent({
      page: '工作流页面',
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: name, 类型: id })
    })
  }

  const handleSetting = data => {
    navigate('/workflow/' + data.id, { replace: true })
  }

  const handleTypeInfo = val => {
    return typeMap.current[val] || '--'
  }
  /* 权限 */
  const [accredit, setAccredit] = useState(false)

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'name',
      title: '工作流',
      width: 260,
      fixed: 'left',
      render: (text, record, _index) => (
        <div className="flexRowStart">
          {record.logo && record.logo !== 'None' && (
            <img
              src={record.logo}
              alt="icon"
              style={{
                height: '36px',
                width: '36px',
                margin: '0 8px 0 0',
                borderRadius: '4px',
                display: 'inline'
              }}
            />
          )}
          <div className="flexCol skills_page_oneCase">
            <Tooltip title={text}>
              <span className="flow-create-page-name domOverflowEllip">{text}</span>
            </Tooltip>
            <Tooltip title={record.description}>
              <span className="flow-create-page-description domOverflowEllip">{record.description}</span>
            </Tooltip>
          </div>
        </div>
      ),
      ellipsis: {
        showTitle: false
      },
      className: 'filelib_name_column'
    },
    // {
    //   dataIndex: 'category_code',
    //   title: t('lib.type'),
    //   width: 100,
    //   render: (text, _record, _index) => handleTypeInfo(text)
    // },
    {
      dataIndex: 'user_name',
      title: t('lib.createUser'),
      width: 140,
      render: (text, _record, _index) => {
        return (
          <div className="flexRowStart">
            <Tooltip title={text}>
              <span className="fileLibPage_user_name domOverflowEllip">{text}</span>
            </Tooltip>
          </div>
        )
      }
    },
    {
      dataIndex: 'create_time',
      title: t('createTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'publish_time',
      title: '发布时间',
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ') || '--'
    },
    {
      dataIndex: 'update_time',
      title: t('updateTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    // {
    //   dataIndex: 'status',
    //   title: '状态',
    //   width: 80,
    //   render: (text, _record, _index) => (text === 1 ? '已发布' : '未发布')
    // },
    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 100,
      render: (_text, record, _index) => (
        <div className="ml-[-16px] bg-inherit">
          {/* <span onClick={() => setAccredit(true)} className="tableSettingName ml-[16px] px-0 text-[#006BFD]">
            授权
          </span> */}
          {/* <span onClick={() => handleEdit(record)} className="tableSettingName ml-[16px] px-0 text-[#006BFD]">
            {t('edit')}
          </span> */}
          <span
            onClick={e => {
              skillsBuriedEvent({
                page: '工作流页面',
                event_name: '【配置】按钮',
                data_id: record.id
              })
              if (!hasFuncPermission([Func.workflow.edit])) {
                return
              }
              handleSetting(record)
            }}
            className="migu-font-400 ml-[16px] cursor-pointer text-[#006BFD] no-underline hover:underline"
          >
            配置
          </span>
          <span onClick={() => handleDelete(record.id)} className="tableSettingName ml-[16px] px-0 text-[#FA514B]">
            {t('delete')}
          </span>
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]

  // table的分页、排序、筛选变化时触发
  const handleTableChange = (values: any) => {
    console.log('values', values)
  }

  if (!hasFuncPermission([Func.workflow.menu], false)) {
    return <NoPermissionTem />
  }
  return (
    <div className="relative h-full min-w-[600px] bg-[#f5f7fb]">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className="filelib-container rounded-[6px]">
        <div className="flexRowJustBet flex py-[24px] pl-[24px] pr-[32px]">
          <div className="flexRowStart">
            {/* <TabsDropComponent
              backColor={'#F5F7FB'}
              list={typeList}
              num={num}
              tabsDropFun={seleCarFun}
              style={{ marginRight: '16px' }}
            ></TabsDropComponent> */}
            <InputAntDef
              searchFun={e => {
                search(e.target.value)
              }}
              placeholder={t('lib.enterName')}
            ></InputAntDef>
          </div>
          <div className=" flex items-center justify-end gap-4">
            <ThemeBtn
              className="migu-font-600 h-[36px] w-[92px]"
              onClick={() => {
                skillsBuriedEvent({
                  page: '工作流页面',
                  event_name: '【创建】工作流按钮'
                })
                if (!hasFuncPermission([Func.workflow.add])) {
                  return
                }
                setInfo({})
                setOpen(true)
              }}
            >
              {t('create')}
            </ThemeBtn>
          </div>
        </div>
        <div className="relative top-[0] h-[calc(100vh-180px)] max-h-[calc(100vh-180px)] overflow-y-scroll px-[24px] scrollbar-hide">
          <TableGrid
            tableInfo={{
              tableData: datalist,
              tableColumns,
              getUniqueKey, // 唯一id
              // tableIsLoading: loading,
              getTableChangeValues: handleTableChange, // 获取table事件
              scrollHeight: 'calc(100vh - 180px)',
              scrollWidth: 1160
            }}
            emptyComponent={
              !loading && !datalist?.length ? (
                <ListEmpty style={{ height: 'calc(100vh - 314px)', margin: 0 }} />
              ) : (
                <div style={{ height: 'calc(100vh - 314px)', background: '#ffffff', margin: 0 }}></div>
              )
            }
          />
        </div>
        {/* fouter */}
        {!loading && datalist?.length > 0 && (
          <FouterPage
            className="filelib-bottom-box filelib-gray-text rounded-[6px]"
            style={{ background: '#FFFFFF' }}
            page={page}
            pageSize={pageSize}
            total={total}
            setPage={newPage => setPage(newPage)}
          ></FouterPage>
        )}
      </div>
      {/* 分配权限 */}
      {accredit && (
        <AccreditDia
          cancel={() => {
            setAccredit(false)
          }}
          submit={() => {
            setAccredit(false)
          }}
        />
      )}
      {open ? (
        <FlowCreate
          open={open}
          setOpen={setOpen}
          obj={info}
          dropList={SearchListDialog}
          submitData={data => {
            handleSetting(data)
            // reload()
          }}
        ></FlowCreate>
      ) : null}
    </div>
  )
}
